package br.com.sgh.dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;

public abstract class DAO<T> implements InterfaceDAO<T>, Serializable {

    private Class<T> classe;
    Session session;

    public DAO(Class<T> classe, Session session) {
        super();
        this.classe = classe;
        this.session = session;
    }

    @Override
    public void salvar(T entity) {
        //session.beginTransaction();
        session.save(entity);
        // session.beginTransaction().commit();
    }

    @Override
    public void atualizar(T entity) {
        session.update(entity);
    }

    @Override
    public void excluir(T entity) {
        session.delete(entity);
    }

    @Override
    public void merge(T entity) {
        session.merge(entity);
    }

    @Override
    public T getEntity(Serializable id) {
        T entity = (T) session.get(classe, id);
        return entity;
    }

    @Override
    public T getEntityByDetachadCriteria(DetachedCriteria criteria) {
        T entity = (T) criteria.getExecutableCriteria(session).uniqueResult();
        return entity;
    }

    @Override
    public List<T> getEntitys() {
        List<T> entitys = session.createCriteria(classe).list();
        return entitys;
    }

    @Override
    public List<T> getListDetachedCriteria(DetachedCriteria criteria) {
        return criteria.getExecutableCriteria(session).list();
    }

    public Criteria criaCriteria() {
        return session.createCriteria(classe);
    }

}
